package yyy.ab.modules.security.session;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;
import yyy.ab.common.core.ResultBean;
import yyy.ab.common.utils.ResponseUtil;
import yyy.ab.common.utils.http.HttpUtils;

import java.io.IOException;

/**
 * 处理 session过期
 * 导致 session 过期的原因有：
 * 1. 并发登录控制
 * 2. 被踢出
 */
public class AbExpiredSessionStrategy implements SessionInformationExpiredStrategy {

    private ObjectMapper mapper = new ObjectMapper();

    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException {
        event.getResponse().setCharacterEncoding("utf-8");
        if (HttpUtils.isAjax(event.getRequest())) {
            ResponseUtil.out(event.getResponse(), ResultBean.errorMsg("登录已失效"));
        } else {
            event.getResponse().sendRedirect("/login");
        }
    }

}
